<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-button type="primary" @click="addRoles">添加角色</el-button>
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 展开列 -->
            <el-row
              :class="['tagBottom',i1 === 0 ? 'tagTop':'','disCenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRoles(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <el-row
                  :clsss="[i2===0?'':'tagTop','disCenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRoles(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="13">
                    <el-tag
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRoles(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#" width="200px"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="userRoles(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户角色的弹窗 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="addClose">
      <el-form :model="addRuleForm" :rules="addRules" ref="addRuleForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolessure">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 用户权限设置的弹窗 -->
    <el-dialog
      title="用户权限设置"
      :visible.sync="settingDialogVisible"
      width="30%"
      @close="settingClose"
    >
      <!-- 树型控件 -->
      <el-tree
        :data="userRolesList"
        :props="myProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="arrID"
        ref="settingRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSetting">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取用户角色列表的存放
      rolesList: [],
      addDialogVisible: false,
      // 添加用户角色的传参
      addRuleForm: {
        // 角色名称
        roleName: "",
        // 角色描述
        roleDesc: ""
      },
      // 添加角色的规则
      addRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" }
        ]
      },
      // 用户权限设置
      settingDialogVisible: false,
      // 获取到的用户权限
      userRolesList: {},
      // 树型控件的使用方式
      myProps: {
        children: "children",
        label: "authName"
      },
      arrID: [],
      // 当前被点击的角色ID
      rolerID: ""
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取用户角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取用户角色列表失败！");
      this.rolesList = res.data;
      //   console.log(res)
    },
    // 删除用户角色权限列表
    async removeRoles(role, roleId) {
      const qwe = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (qwe != "confirm") return this.$message.info("删除用户信息失败！");
      const { data: ret } = await this.$http.delete(
        `roles/${role.id}/rights/${roleId}`
      );
      if (ret.meta.status !== 200)
        return this.$message.error("获取用户权限失败！");
      this.$message.success("删除用户权限成功！");
      role.children = ret.data;
    },
    // 点击添加用户角色显示弹窗
    addRoles() {
      this.addDialogVisible = true;
    },
    // 窗口关闭后重置表单
    addClose() {
      this.$refs.addRuleForm.resetFields();
    },
    // 添加用户角色点确定
    addRolessure() {
      // 预校验
      this.$refs.addRuleForm.validate(async valid => {
        if (!valid) return;
        // 发起请求
        const { data: res } = await this.$http.post("roles", this.addRuleForm);
        if (res.meta.status !== 201)
          return this.$message.error("添加用户角色失败！");
        this.$message.success("添加用户角色成功！");
      });
      this.getRolesList();
      this.addDialogVisible = false;
    },
    // 修改用户角色的按纽
    // 获取角色权限列表
    async userRoles(role) {
      // 将当前点击的角色的ID保存下来
      this.rolerID = role.id;
      // 发起请求获取列表
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200)
        return this.$message.error("获取用户角色权限失败！");
      // this.$message.success("获取用户角色权限成功！");
      // console.log(res.data);
      this.userRolesList = res.data;

      this.getsnalevList(role, this.arrID);

      this.settingDialogVisible = true;
    },
    // 获取三级节点的ID并存放到数组中
    getsnalevList(node, arr) {
      // 判断节点是否为三级，三级没有children
      if (!node.children) return arr.push(node.id);
      node.children.forEach(item => {
        this.getsnalevList(item, arr);
      });
    },
    // 监听关闭事件，重置表单
    settingClose() {
      this.arrID = [];
    },
    // 将勾选的权限提交
    async saveSetting() {
      const ID = [
        this.$refs.settingRef.getCheckedKeys(),
        this.$refs.settingRef.getHalfCheckedKeys()
      ];
      const idStr = ID.join(",");
      // 将str提交
      const { data: res } = await this.$http.post(
        `roles/${this.rolerID}/rights`,
        {
          rids: idStr
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("添加用户权限失败!");
      this.$message.success("添加用户权限成功！");
      this.getRolesList();
      this.settingDialogVisible = false;
    }
  }
};
</script>

<style lang='less' scoped>
.el-tag {
  margin: 10px;
}
.tagTop {
  border-top: 1px solid #ddd;
}
.tagBottom {
  border-bottom: 1px solid #ddd;
}
.disCenter {
  display: flex;
  align-items: center;
}
</style>